#include "common.h"
#include "dbm.h"
#include "net.h"
#ifdef ZM_SPEC
#include "zm_spec.h"
#endif


int main(int argc, char *argv[])
{
	int sockfd = -1;
	struct sockaddr_in client_addr;
	socklen_t sock_len = sizeof(struct sockaddr_in);
	char sendbuff[SND_BUF_LEN]={0};
	char recvbuff[RCV_BUF_LEN]={0};
	int send_len = 0, recv_len = 0;
	int cnt = 0, i = 0,ret = 0;
 
 	// init zlog
 	if(dzlog_init(LOG_CONF_FILE,ZM_SPEC_CAT)<0)
 	{
 		printf("dzlog_init failed.\n");
 		exit(EXIT_FAILURE);
 	}
 
	sockfd = create_bind_udp_socket(LOCAL_PORT,1);
	if(sockfd < 0)
	{
		dzlog_error("create_bind_socket failed.\n");
		exit(EXIT_FAILURE);
	}
	dzlog_debug("create_bind_socket success,sockfd = %d.\n",sockfd);

	// init database
	if(db_init(DATABASE_NAME,IPC_TABLE_NAME)<0)
	{
		dzlog_error("database init error!\n");
		exit(EXIT_FAILURE);
	}

#ifdef ZM_SPEC
	zm_build_get_status(sendbuff,&send_len);
	dzlog_debug("sendbuff len = %d\n",send_len);
#endif
	if(broadcast_message(sockfd,sendbuff,send_len)<0)
	{
		dzlog_error("broadcast error!\n");
		exit(EXIT_FAILURE);
	}
	memset(&client_addr,0,sizeof(struct sockaddr_in));
	
#ifdef ZM_SPEC
	Device_Stat_Info data;
	memset(&data, 0, sizeof(Device_Stat_Info));
#endif
	dzlog_debug("time cnt = %d\n",cnt);
	dzlog_info("searching ipcameras.....please wait...\n");

	cnt = SEARCH_TIME*1000*1000/HUNDRED_MSEC;
	while(cnt--)
	{
		ret = recvfrom(sockfd,recvbuff,RCV_BUF_LEN,0,(struct sockaddr*)&client_addr,&sock_len);
		if(ret > 0)
		{
#ifdef ZM_SPEC
			recv_len = sizeof(Device_Stat_Info);
			if(zm_parse_packet(recvbuff,(void*)&data,&recv_len,GET_DEV_STATUS)<0)
			{
				dzlog_error("parse recvbuff error.\n");
				memset(recvbuff,0,RCV_BUF_LEN);
			}
			else
			{
				// add data to sqlite database
				dzlog_info(">>>%02d %s\n",i++, data.dev_id);
				db_insert_ipc(IPC_TABLE_NAME,(const void*)&data,SPEC_ZM);
				db_insert_hist(HISTORY_TABLE_NAME,(const void*)&data,SPEC_ZM);
			}
#endif
		}
		else
		{
			dzlog_debug("recvfrom error:%s\n",strerror(errno));
		}
		usleep(HUNDRED_MSEC);
	}
	dzlog_info("searched ipcameras number: %d\n", i);

 	// exit zlog
 	zlog_fini();
	// close db
	db_exit();
 
 	exit(EXIT_SUCCESS);
}
 
